package com.imut.lagain.controller;

import com.imut.lagain.entity.UserRole;
import com.imut.lagain.service.IUserRoleService;
import com.imut.lagain.util.JwtUtil;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户角色控制器
 */
@RestController
@RequestMapping("/api/user-roles")
@RequiredArgsConstructor
public class UserRoleController {
    private static final Logger log = LoggerFactory.getLogger(UserRoleController.class);

    private final IUserRoleService userRoleService;
    private final JwtUtil jwtUtil;

    /**
     * 设置用户角色
     */
    @PostMapping("/setup")
    public ResponseEntity<Map<String, Object>> setupRole(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody RoleSetupRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            UserRole userRole = userRoleService.setupUserRole(userId, request.getRoleType(), 
                    request.getRoleName(), request.getAdminPassword());
            
            if (userRole != null) {
                response.put("success", true);
                response.put("message", "角色设置成功");
                response.put("data", userRole);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "角色设置失败");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("设置用户角色失败", e);
            response.put("success", false);
            response.put("message", "设置角色失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取当前用户角色
     */
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentRole(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            UserRole userRole = userRoleService.getUserRole(userId);
            response.put("success", true);
            response.put("data", userRole);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取用户角色失败", e);
            response.put("success", false);
            response.put("message", "获取角色失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 验证管理员密码
     */
    @PostMapping("/validate-admin-password")
    public ResponseEntity<Map<String, Object>> validateAdminPassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody PasswordValidateRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean isValid = userRoleService.validateAdminPassword(userId, request.getPassword());
            response.put("success", isValid);
            response.put("message", isValid ? "密码验证成功" : "密码验证失败");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("验证管理员密码失败", e);
            response.put("success", false);
            response.put("message", "密码验证失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新管理员密码
     */
    @PutMapping("/admin-password")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> updateAdminPassword(
            @RequestHeader("Authorization") @NotBlank String authorization,
            @Valid @RequestBody PasswordUpdateRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            boolean success = userRoleService.updateAdminPassword(userId, 
                    request.getOldPassword(), request.getNewPassword());
            
            if (success) {
                response.put("success", true);
                response.put("message", "密码更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "密码更新失败，请检查旧密码是否正确");
                return ResponseEntity.badRequest().body(response);
            }
            
        } catch (Exception e) {
            log.error("更新管理员密码失败", e);
            response.put("success", false);
            response.put("message", "密码更新失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取所有管理员
     */
    @GetMapping("/admins")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> getAllAdmins(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<UserRole> admins = userRoleService.getAllAdmins();
            response.put("success", true);
            response.put("data", admins);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取管理员列表失败", e);
            response.put("success", false);
            response.put("message", "获取管理员列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取所有伴侣
     */
    @GetMapping("/partners")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> getAllPartners(
            @RequestHeader("Authorization") @NotBlank String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            List<UserRole> partners = userRoleService.getAllPartners();
            response.put("success", true);
            response.put("data", partners);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("获取伴侣列表失败", e);
            response.put("success", false);
            response.put("message", "获取伴侣列表失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 角色设置请求类
     */
    public static class RoleSetupRequest {
        @NotBlank(message = "角色类型不能为空")
        private String roleType;
        
        private String roleName;
        
        private String adminPassword;
        
        public String getRoleType() {
            return roleType;
        }
        
        public void setRoleType(String roleType) {
            this.roleType = roleType;
        }
        
        public String getRoleName() {
            return roleName;
        }
        
        public void setRoleName(String roleName) {
            this.roleName = roleName;
        }
        
        public String getAdminPassword() {
            return adminPassword;
        }
        
        public void setAdminPassword(String adminPassword) {
            this.adminPassword = adminPassword;
        }
    }

    /**
     * 密码验证请求类
     */
    public static class PasswordValidateRequest {
        @NotBlank(message = "密码不能为空")
        private String password;
        
        public String getPassword() {
            return password;
        }
        
        public void setPassword(String password) {
            this.password = password;
        }
    }

    /**
     * 密码更新请求类
     */
    public static class PasswordUpdateRequest {
        @NotBlank(message = "旧密码不能为空")
        private String oldPassword;

        @NotBlank(message = "新密码不能为空")
        private String newPassword;

        public String getOldPassword() {
            return oldPassword;
        }

        public void setOldPassword(String oldPassword) {
            this.oldPassword = oldPassword;
        }

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }
}